#### LAB 6 ####

### Getting data in

#read data
daphnia = read.table("V:\\My Documents\\ENT420\\lab\\lab6_data.txt", sep="\t", header=T)

#circle plot of log(lakearea) at spatial coordinates
symbols(daphnia$x,daphnia$y,circles=log(daphnia$area),inches=0.2)

# color-code presence / absence (1/0) - vector of colors (red = pres. / white = absence)
color = ifelse(daphnia$now==1, "red", "white")

# plot with color fill
symbols(daphnia$x,daphnia$y, circles=log(daphnia$area), inches=.2, bg=color)

# plot p/a against log-area
plot(daphnia$area, daphnia$now, log="x")


### Logistic Regression

#log area variable 
daphnia$larea = log(daphnia$area)

# logistic regression
fit = glm(now ~ larea, family = binomial(), data = daphnia)
summary(fit)

#extract regression coefficients ( from m + b1x1 + b2x2.... get m and the set of bX values)
fit$coef

# odds of presence for a 1ha lake (m)
exp(fit$coef[1])

# slope measures how much the logg-odds change... (b)
exp(fit$coef[2])

# x3 increase in lake area.... odds increase by 1.5
exp(fit$coef[1]+2*fit$coef[2])

#plot p/a against log area
plot(daphnia$larea, daphnia$now)

a=fit$coef[1]
b=fit$coef[2]
p.fun = function(x)
{
exp(a+b*x)/(1+exp(a+b*x))
}
curve(p.fun, 0, 10, add=T)